package com.yunshipei.core.utils;

import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import android.view.inputmethod.InputMethodManager;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtils {

    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    public static String getHost(String url) {
        if (TextUtils.isEmpty(url)) return "";
        Uri uri = Uri.parse(url);
        if (uri != null) {
            return uri.getHost()+":8000";
        }
        return "";
    }

    public static void hideKeyBoard(Context context) {
        Activity activity = (Activity) context;
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && activity.getCurrentFocus() != null) {
            if (activity.getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    public static String getUrlParams(String url, String params) {
        Uri uri = Uri.parse(url);
        if (uri == null) {
            return "";
        }
        String value = uri.getQueryParameter(params);
        return TextUtils.isEmpty(value) ? "" : value;
    }

    public static String removeParams(String url, String[] params) {
        StringBuilder ps = new StringBuilder();
        ps.append("(");
        for (String param : params) {
            ps.append(param).append("|");
        }
        ps.deleteCharAt(ps.length() - 1);
        ps.append(")");
        String reg = "(?<=[\\?&])" + ps.toString() + "=[^&]*&?";
        url = url.replaceAll(reg, "");
        url = url.replaceAll("(\\?|&+)$", "");
        return url;
    }
}
